//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Xml;
using CommunityServer.Components;
using CommunityServer.Configuration;

namespace CommunityServer.Galleries.Components
{
	/// <summary>
	/// Summary description for RebuildThumbnailsJob.
	/// </summary>
	public class ImportPhotoJob : IJob
	{
		public ImportPhotoJob() { }

		public void Execute(XmlNode node)
		{
			Queue queue = CSCache.Get("GalleryImportItems") as Queue;
			int items;

			if((queue != null) && (queue.Count > 0))
			{
				// Get how many items to process
				try { items = int.Parse(node.Attributes["picturesPerRun"].Value); }
				catch { items = 25; }

				// See if limiting items is 0 or less (do all of them)
				if(items <= 0)
					items = queue.Count;

				for(int i = ((queue.Count < items) ? queue.Count : items) - 1 ; i >= 0 ; i--)
				{

					ImportItem item = queue.Dequeue() as ImportItem;
					
					try
					{

						// The file may have already been regenerated, skip it
						if(!File.Exists(item.Filename))
							continue;

						CSContext.Create(item.Gallery.SettingsID);
						CSContext.Current.User = item.User;

						FileInfo file = new FileInfo(item.Filename);

						GalleryPost post = new GalleryPost();
						post.Username = item.User.Username;
						post.SectionID = item.Gallery.SectionID;
						post.ParentID = 0;
						post.GalleryPostType = GalleryPostType.Image;
						post.PostID = -1;

						post.Subject = "";
						post.Excerpt = "";
						post.Body = "";
						post.PostType = PostContentType.HTML;
						post.FormattedBody = null;

						if(item.Categories != null)
							post.Categories = item.Categories;


						post.PostDate = DateTime.Now;
						//post.UserTime = UserTime.ConvertToUserTime(post.PostDate, item.User.);

						//Get the file
						FileStream stream = file.OpenRead();
						ImageInfo image = new ImageInfo(stream) ;

					
						if(!image.Check())
						{
							stream.Close();
							continue;
						}

						PostAttachment attachment = new PostAttachment(file.Name, image.MimeType , stream);

						// Create the picture in the database
						GalleryPosts.CreatePicture(item.Gallery.SectionID, post, attachment);
						
						//make the thumbnail
						ImageHandling.ScalePicture(post, item.Gallery.GetThumbnailSettings());

                        stream.Close();

						file.Delete();
					}
					catch(Exception e)
					{
						Debug.WriteLine( e.Message + " : " + ( e.InnerException != null ? e.InnerException.Message : String.Empty ) );
						CSException fe = new CSException( CSExceptionType.UnknownError, "ImportPhotos Failed on: " + item.Filename, ( e.InnerException != null ? e.InnerException : e ) );
						fe.Log(item.Gallery.SettingsID);
					}
				}

				// If the queue is empty, then remove it
				if(queue.Count <= 0)
					CSCache.Remove("GalleryImportItems");
			}
		}
	}
}
